/*
 * @Descripttion: 
 * @Author: chendingfengmail@163.com
 * @version: 
 * @Date: 2021-04-07 09:55:14
 * @LastEditors: luozhenfu
 * @LastEditTime: 2023-02-18 16:01:16
 */
import cookies from './util.cookies'
import db from './util.db'
import log from './util.log'
import compatibility from './util.compatibility';
import date from './util.date'
import commons from './util.commons'
// import download from './util.download'
import region from './util.region'
import crypto from 'crypto'
import url from './util.url';

const util = {
  cookies,
  db,
  log,
  date,
  commons,
  compatibility,
  // download,
  region,
  url,
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'amp-link')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('amp-link'))
}

/**
 * 过滤对象数组
 * @param {obj} params     
 * @param {[]} objArr 
 */
util.filterObjArr = function (params, objArr) {
  let conditions = {};
  let filterArr = [];
  for (const key in params) {
    if (params[key] != '') {
      conditions[key] = params[key];
    }
  }
  if (Object.keys(conditions).length == 0) {
    return objArr;
  }
  if (objArr != '' && objArr != undefined) {
    filterArr = objArr.filter((item) => {
      let flag = true;
      for (const key in conditions) {
        if (!(item[key] != undefined && item[key] == conditions[key])) {
          flag = false;
        }
      }
      if (flag) {
        return item;
      }
    })
  }
  return filterArr;
}

/**
 * 生成随机码
 * @returns
 */
util.createUniqueString = function () {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
};

/**
 * 生成UUID
 */
util.generateUUID = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010 
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01 
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}

/**
 * 判断数值区间
 * @param {*} str 
 * @param {*} maxnum 
 * @param {*} minnum 
 * @returns 
 */
util.isRangeIn = function (str, maxnum, minnum) {
  var num = parseFloat(str);
  if (num <= maxnum && num >= minnum) {
    return true;
  }
  return false;
}

/**
 * ArrayBuffer转字符串
 * @param {*} u 
 * @param {*} f 
 */
util.ab2str = function (u, f) {
  let b = new Blob([u]);
  let r = new FileReader();
  r.readAsText(b, 'utf-8');
  r.onload = function () { if (f) f.call(null, r.result) }
}

/**
 * 将二进制字符串转换成Unicode字符串
 * @param {*} str 
 * @returns 
 */
util.binaryToStr = function (str) {
  let result = [];
  let list = str.split(" ");
  for (let i = 0; i < list.length; i++) {
    let item = list[i];
    let asciiCode = parseInt(item, 2);
    let charValue = String.fromCharCode(asciiCode);
    result.push(charValue);
  }
  return result.join("");
}

// 返回市场名称
util.showMarketName = function (code, list) {
  var name = "";
  list.forEach(item => {
    if (code == item.code) {
      name = item.name;
    }
  });
  return name
}

// 返回对象数组的索引值
util.arrIndex = function (arr, obj) {
  var index = null;
  let key = Object.keys(obj)[0];
  arr.every(function (value, i) {
    if (value[key] === obj[key]) {
      index = i;
      return false;
    }
    return true;
  })
  return index;
}

/**
 * 
 * @param {*} list 集合
 * @param {*} pid 父节点,默认0顶级
 * @param {*} parentCodeName 父节点别名
 * @param {*} code 节点别名
 * @returns 
 * 例子：let temp = util.listToTree(result.value, 0, 'parentCode');
 */
util.listToTree = function (list, pid = 0, parentCodeName = 'parentCode', code = 'code') {
  if (!Array.isArray(list)) {
    return [];
  }
  let tempList = JSON.parse(JSON.stringify(list))
  function fn(data, parentCode) {
    let result = [], temp;
    for (let item of data) {
      if (item[parentCodeName] == parentCode) {
        temp = fn(data, item[code]);
        if (temp.length > 0) {
          item.children = temp;
        }
        result.push(item);
      }
    }

    return result;
  }
  return fn(tempList, pid)
};

/**
 * 树列表深度优先遍历 => 先序遍历。
 * @param {*} tree 树列表
 * @returns 数组数据
 */
util.treeConvertToList = function (tree) {
  let tempArray = []
  if (!tree) {
    return tempArray;
  }
  function treeForeach(tree, func) {
    tree.forEach(data => {
      func(data)
      data.children && treeForeach(data.children, func) // 遍历子树
    })
  }
  treeForeach(tree, node => { tempArray.push(node) })
  return tempArray
};

/**
 * 深度优先遍历，先序遍历，查找树节点
 * @param {*} tree 树列表
 * @param {*} id 对象字段
 * @returns 树节点
 */
util.searchTreeNode = function (tree, id) {
  let temp = ''
  function treeForeach(tree, func) {
    for (let data of tree) {
      if (func(data)) {
        temp = data
        return;
      }
      data.children && treeForeach(data.children, func) // 遍历子树
    }
  }
  treeForeach(tree, node => node.id === id)
  return temp
};

/**
 * 根据列表生成菜单树
 * @param {*} list 
 * @param {*} getLeaf 是否返回叶节点id数组 默认不反悔
 * @returns 
 */
util.menuTree = function (list, getLeaf) {
  // 一级父菜单
  let parents = list.filter(item => item.pid == null || item.pid == undefined)
  // 子菜单列表
  let childrens = list.filter(item => item.pid);
  // 叶节点
  var leafNodeIds = [];
  // 生成父菜单
  function translator(parents, childrens) {
    // 查询每个父菜单子菜单
    parents.forEach(element => {
      childrens.forEach((children, index) => {
        if (children.pid == element.id) {
          // 从子菜单列表删除
          let temp = JSON.parse(JSON.stringify(childrens));
          temp.splice(index, 1);
          // 添加到父菜单儿子列表
          element.children ? element.children.push(children) : element.children = [children];
          translator([children], temp);
          if (!children.children || children.children.length == []) {
            leafNodeIds.push(children.id)
          }
        }
      })
    })
  }
  // 生成菜单树
  translator(parents, childrens);
  if (!getLeaf) {
    return parents;
  } else {
    let menuTree = {
      treeData: parents,
      leafNodeIds: leafNodeIds
    }
    return menuTree;
  }
}

/**
 * 查找keys数组中 属于树的叶节点数组
 * @param {*} leaf 树数据叶子节点数组
 * @param {*} keys 原keys数组
 */
util.renderMenuTreeKeys = function (leaf, keys) {
  let findLeafArr = [];
  keys.forEach(key => {
    let findLeaf = leaf.find(item => item == key);
    findLeaf ? findLeafArr.push(findLeaf) : '';
  });
  return findLeafArr;
}

/**
 * 根据列表生成权限树
 * @param {*} list 
 */
util.rightTree = function (list) {
  var rightTree = [];
  list.forEach(item => {
    let parentRight = {
      module: item.module,
      label: item.moduleName,
      isIndeterminate: false, // 全选框状态
      selectAll: false, // 是否全选
      selected: [], // 已选择列表
      childs: [], // 选项
    }
    let childRight = {
      id: item.id,
      app: item.app,
      groups: item.groups,
      name: item.name,
      module: item.module,
      moduleName: item.moduleName,
      label: item.description
    }
    if (rightTree.length > 0) {
      var index = 0;
      let findNode = rightTree.find(node => {
        if (node.module == item.module) {
          return node;
        }
        index++;
      })
      if (!findNode) {
        parentRight['childs'].push(childRight);
        rightTree.push(parentRight);
      } else {
        rightTree[index]['childs'].push(childRight);
      }
    } else {
      parentRight['childs'].push(childRight);
      rightTree.push(parentRight);
    }
  });
  console.log('rightTree', rightTree);
  return rightTree;
}

/**
 * 根据接口id数组 渲染权限数组已勾选状态
 * @param {Array} data 权限数组
 * @param {Array} interfaces 接口id数组
 */
util.renderRightData = function (data, interfaces) {
  data.forEach(item => {
    let arr = [];
    item.childs.forEach(child => {
      if (interfaces.length > 0) {
        interfaces.forEach(intf => {
          if (child.id == intf) {
            arr.push(intf); // 缓存接口数组
            interfaces.unshift(); // 删除已选择接口
          }
        });
      }
    });
    if (arr.length) {
      // 已选择数组
      item.selected = arr;
      // 是否全选状态
      item.selectAll = arr.length == item.childs.length ? true : false;
      // 是否半选状态
      item.isIndeterminate = !item.selectAll && item.selected.length > 0 && item.selected.length < item.childs.length ? true : false;
    }
  });
  return data;
}

/**
 * 
 * @param {*} blob 二进制流转blob
 * @param {*} fileName 保存的文件名称
 */
util.fileDownloadBlob = function (blob, fileName, sufix = '.xlsx') {
  let tempBlob = new Blob([blob], { type: "application/vnd.ms-excel;charset=utf-8", });
  // 浏览器内核
  let browser = {
    kernel: function () {
      let u = navigator.userAgent;
      let versions = {
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Firefox') > -1, //火狐内核Gecko
      }
      for (const key in versions) {
        if (versions[key]) {
          return key;
        }
      }
    }()
  }
  // IE
  if (browser.kernel == 'trident') {
    window.navigator.msSaveOrOpenBlob(tempBlob, fileName);
  } else {
    // 谷歌
    let downloadElement = document.createElement("a");
    downloadElement.href = window.URL.createObjectURL(tempBlob);
    downloadElement.download = fileName + sufix;
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(downloadElement.href); //释放掉blob对象
  }
}

/**
 * md5加密
 */
util.getmd5 = function (pwd) {
  if (pwd == null || undefined == pwd) {
    return '';
  }
  var md5 = crypto.createHash("md5");
  md5.update(pwd);
  return md5.digest('hex');
}

/**
 *  字典过滤
 * @param {*} obj 字典对象
 * @param {*} notObjType 过滤非object类型的字段
 * @param {*} dataType 字典数据类型 1、集合 2、数
 */
util.distFilter = function (obj, notObjType=false, dataType=1) {
  let data = JSON.parse(JSON.stringify(obj));
  for(let key in data){
    if(notObjType){
      if((!((typeof data[key]) == 'object')) || dataType == data[key].dataType){
       delete data[key];
      }
    }else{
      if((dataType == data[key].dataType)){
       delete data[key];
      }
    }
  }
  return data;
}

/**
 *  通过value取字典对象
 * @param {*} obj 字典对象
 * @param {*} dataType 字典value
 */
util.getDistByValue = function(obj,value){
  for(let key in obj){
    if(obj[key].value == value){
      return obj[key];
    }
  }
  return {};
}

/**
 * 文件选择
 * @param {*} data 
 * @param {*} callback 
 */
util.selectFile = function(data, callback) {
  // 动态创建文件元素
  var input = document.createElement('input');
  input.type = 'file';
  // 文件选择事件
  input.onchange = e => {
    // 获取选择的文件
    var file = e.target.files[0];
    try {
      // 回调文件处理
      if(callback) {
        callback(data, file);
      }
      input.remove();
    } catch (error) {
      input.remove();
    }
  }
  // 触发文件选择按钮
  input.click();
}

export default util;
